<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog">
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                :disabled="true"
                placeholder="请选择领入仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectDepotStorage"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-deptName>
              <el-input
              v-if="systemConfig.use_application_store_depot_required_strategy === 0"
                class="not-mongolia"
                :disabled="true"
                placeholder="请选择领入部门"
                v-model="formInfo.data.deptName"
              >
                <template #append>
                  <el-icon @click="selectDept"><Search /></el-icon>
                </template>
              </el-input>
              <el-input
                v-if="systemConfig.use_application_store_depot_required_strategy === 1"
                :disabled="true"
                placeholder="请选择领用部门"
                v-model="formInfo.data.deptName"
              />
            </template>
            <template v-slot:form-exportDepotName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择领出仓库"
                v-model="formInfo.data.exportDepotName"
              >
                <template #append>
                  <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div v-if="formInfo.data.deptId" class="model-panel">
        <div class="model-panel-title">
          <p>详情信息</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            :query="filterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="filterInfo.searchList"
            :filter-btn="filterInfo.searchBtn"
          >
            <template v-slot:filter-fill>
              <el-checkbox
                v-model="filterInfo.data.fill"
                label="只显示领出仓库可用数量>0产品"
                border
                @change="changeCheck"
              ></el-checkbox>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <CardList
              :tableData="tableInfo.data"
              :total="tableInfo.total"
              @getList="getCardList"
              @addCart="addCart"
            />
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择领入仓库 -->
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:showDialog="depotInfo.visible"
      @callback="selectStoreDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :query="depotInfo.query"
      :highlightRow="true"
    />
    <!-- 选择部门 -->
    <SelectDept
      v-if="deptInfo.visible"
      v-model:showDialog="deptInfo.visible"
      :query="deptInfo.query"
      @callback="selectDeptCallback"
      :checkBox="false"
      :highlightRow="true"
    />
    <!-- 选择领出仓库 -->
    <SelectDepot
      v-if="exportDepotInfo.visible"
      v-model:showDialog="exportDepotInfo.visible"
      @callback="selectExportDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :api="exportDepotInfo.api"
      :query="exportDepotInfo.query"
      :highlightRow="true"
    />
  </div>
</template>

<script setup name="useApplicationCard">
import { getCustomizeSetting } from '@/api/customize'
import {
  getProductWithOtherCustomizeList,
  getDepotById,
  getDepotPage,
  addApplicationCart,
} from '@/api/core'
import { applicationValidateSubDepot } from '@/api/use'
const CardList = defineAsyncComponent(() => import('./cardList'))
import utils from '@/common/js/utils'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id'])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
//表单相关
const formInfo = ref({
  ref: null,
  supDepotIds: proxy.$store.state.user.userInfo.coreResourcesVO
    ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
        '1'
      ) !== -1 &&
      proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !== 1
      ? proxy.$store.state.user.userInfo.coreResourcesVO.supDepotIds || []
      : ''
    : '',
  data: {
    deptId: '',
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1 &&
        proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !==
          1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1 &&
        proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !==
          1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    exportDepotName: '',
    exportDepotId: '',
  },
  fieldList: [
    {
      label: '领入仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '领入部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '领出仓库',
      value: 'exportDepotName',
      type: 'slot',
    },
    {
      label: '领出部门',
      value: 'exportDeptName',
      type: 'input',
      disabled: true,
    },
  ],
  rules: {
    depotName: [
      {
        required:
          systemConfig.value.use_application_store_depot_required_strategy === 1
            ? true
            : false,
        message: '请选择领入仓库',
        trigger: 'change',
      },
    ],
    deptName: [
      {
        required: true,
        message: '请选择领入仓库',
        message: '请选择领入部门',
        trigger: 'change',
      },
    ],
    exportDepotName: [
      {
        required:
          systemConfig.value.use_application_export_depot_required_strategy === 1
            ? true
            : false,
        message: '请选择领出仓库',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    curPage: 1,
    page: true,
    pageSize: 12,
    customizeUserVO: {},
    sortString: '',
    copyQuery: {},
    queryMap: {
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      exportStockQty: {
        queryType: 'NOT_IN',
        value: systemConfig.value.allow_use_qty_greater_stock == '0' ? 0 : null,
      },
    },
    queryParams: {},
  },
  data: {
    fill: systemConfig.value.allow_use_qty_greater_stock == '0' ? true : false,
  },
  searchList: [],
  searchBtn: [
    { type: 'slot', value: 'fill' },
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  tableKey:
    'useApplicationOrderModifyProductWithOther-com.slip.spd.entity.vo.core.CoreProductWithOtherVO',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      userDeptId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      exportDepotId: '',
      storeDepotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1 &&
          proxy.$store.state.user.userInfo.coreResourcesVO
            .isCargoSpaceManage !== 1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      checkDeptProduct: 1,
      isDeptProduct: 1,
      deptId: proxy.$store.state.user.userInfo.dept
        ? proxy.$store.state.user.userInfo.dept.id
        : '',
      forbidden: 1,
    },
  },
})
const tableInfo = ref({
  data: [],
  total: 0,
})
const depotInfo = ref({
  visible: false,
  depotType: '',
  query: {
    idNot: '',
    useTypeId: '1',
    status: '1',
    depotAuth: 'id',
  },
})
const deptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const exportDepotInfo = ref({
  visible: false,
  depotType: '',
  api: getDepotPage,
  query: {
    useTypeId: '1',
    status: '1',
    idMult: '',
    idNot: '',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

onMounted(() => {
  formInfo.value.data.depotId = proxy.$store.state.user.userInfo.coreResourcesVO
    ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
        '1'
      ) !== -1 &&
      proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !== 1
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    : ''
  setData()
  getDepot()

  //领出仓库必填时自动带出领出仓库
  if (systemConfig.value.use_application_export_depot_required_strategy === 1) {
    //领出仓库
    getExportDopotId(formInfo.value.data.depotId)
  }
})
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      hidden: true,
      type: 'column',
      show: false,
      formatter: proxy.$fn.TripartiteMethod,
    },
    storeStockQty: {
      label: '领入仓库可用数量',
      value: 'storeStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
      componentType: 'number',
      show: false,
    },
    exportStockQty: {
      label: '领出仓库可用数量',
      value: 'exportStockQty',
      hidden: true,
      type: 'column',
      formatter: utils.qtyFormatter,
      componentType: 'number',
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      show: false,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    showPrice: {
      label: '展示价格',
      value: 'showPrice',
      type: 'column',
      show: false,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
    editQty: {
      label: '数量',
      value: 'editQty',
      type: 'slot',
      componentType: 'number',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
  }
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getProductCustomize()
}
function getProductCustomize() {
  let param = {
    tableKey: productInfo.value.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
      if (formInfo.value.data.deptId) {
        getProductList()
      }
    }
  })
}
function getProductList() {
  filterInfo.value.query.queryParams = {
    exportDepotId: formInfo.value.data.exportDepotId,
    storeDepotId: formInfo.value.data.depotId,
    checkDeptProduct: 1,
    forbidden: 1,
    isDeptProduct: 1,
    deptId: formInfo.value.data.deptId,
    userDeptId: formInfo.value.data.deptId,
  }
  filterInfo.value.query.queryMap = {
    ...filterInfo.value.query.queryMap,
    ...productInfo.value.query.queryMap,
  }
  if (systemConfig.value.use_application_dept_product_strategy === 1) {
    // 领用入库部门
    filterInfo.value.query.queryParams.userDeptId = formInfo.value.data.deptId
  } else {
    // 申请人所在部门
    filterInfo.value.query.queryParams.userDeptId = proxy.$store.state.user
      .userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : ''
  }
  getProductWithOtherCustomizeList(filterInfo.value.query).then((res) => {
    if (res && res.data) {
      console.log(res.data)
      tableInfo.value.total = res.total
      const data = res.data.map(function (item) {
        return {
          ...item,
          productId: item.id,
          price: item.price,
          defaultSupplierPrice: item.price,
          defaultSupplierId: item.supplierId,
          defaultSupplierName: item.supplierName,
          defaultSupplierCode: item.supplierCode,
          storeStockQty: item.storeStockQty || 0,
          exportStockQty: item.exportStockQty || 0,
        }
      })
      tableInfo.value.data = data
    }
  })
}
function getExportDopotId(depotId) {
  let exportDepotQuery = {
    subDepotId: depotId,
    searchType: 'depot',
    status: '1',
    useTypeId: '1',
    sort: 'create_time desc',
  }
  getDepotPage(exportDepotQuery).then((res) => {
    if (res.success && res.data && res.data.length > 0) {
      for (let i = 0; i < res.data.length; i++) {
        if (!res.data[i].lock) {
          formInfo.value.data.exportDepotId = res.data[i].id
          formInfo.value.data.exportDepotName = res.data[i].name
          productInfo.value.query.queryParams.exportDepotId = res.data[i].id
          getProductList()
          break
        }
      }
    }
  })
}
function getDepot() {
  if (formInfo.value.data.depotId && formInfo.value.data.depotId !== -2) {
    getDepotById(formInfo.value.data.depotId).then((res) => {
      if (res && res.success) {
        formInfo.value.data.deptId = res.data.deptId
      }
    })
  }
}
function getCardList(obj) {
  filterInfo.value.query.curPage = obj.curPage
  filterInfo.value.query.pageSize = obj.pageSize
  getProductList()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  filterInfo.value.data.fill = false
  search()
}
function changeCheck(type) {
  //【领用申请】新增领用申请单-选择产品 页面 增加一个checkbox框 只显示领出仓库可用数量>0产品
  if (type) {
    filterInfo.value.query.queryMap.exportStockQty.value = 0
  } else {
    filterInfo.value.query.queryMap.exportStockQty.value = null
  }
  search()
}
function search() {
  getProductList()
}
//选择领入仓库
function selectDepotStorage() {
  depotInfo.value.depotType = 'storage'
  depotInfo.value.query.depotAuth = 'id'
  depotInfo.value.visible = true
  depotInfo.value.query.subDepotId = ''
  depotInfo.value.query.isCargoSpaceManage = 0
}
function selectDept() {
  deptInfo.value.visible = true
  deptInfo.value.query.idNot = formInfo.value.data.deptId
}
//选择领出仓库
function selectDepotExport() {
  // if (!formInfo.value.data.depotId) {
  //   proxy
  //     .$confirm('请选择领出仓库', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     })
  //     .then(() => {
  //       selectDepotStorage()
  //     })
  //   return
  // }
  exportDepotInfo.value.depotType = 'export'
  exportDepotInfo.value.api = getDepotPage
  exportDepotInfo.value.query.idMult = formInfo.value.supDepotIds.length
    ? formInfo.value.supDepotIds.toString()
    : ''
  if (!formInfo.value.data.depotId) {
    exportDepotInfo.value.query.idNot = formInfo.value.data.exportDepotId
  } else {
    exportDepotInfo.value.query.idNot =
      formInfo.value.data.depotId +
      (formInfo.value.data.exportDepotId
        ? ',' + formInfo.value.data.exportDepotId
        : '')
  }
  // exportDepotInfo.value.query.idNot =
  //   formInfo.value.data.depotId +
  //   (formInfo.value.data.exportDepotId
  //     ? ',' + formInfo.value.data.exportDepotId
  //     : '')
  exportDepotInfo.value.visible = true
}
function selectStoreDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.value.data.depotId !== row.id) {
      tableInfo.value.data = []
      formInfo.value.data.depotId = row.id
      formInfo.value.data.depotName = row.name
      formInfo.value.data.deptName = row.deptName
      formInfo.value.data.deptId = row.deptId
      formInfo.value.supDepotIds = row.supDepotIds
      formInfo.value.data.exportDepotName = ''
      formInfo.value.data.exportDepotId = ''
      formInfo.value.data.exportDeptName = ''
      formInfo.value.data.exportDeptId = ''
    }
    productInfo.value.query.queryParams.storeDepotId = row.id
    //领出仓库必填时自动带出领出仓库
    if (
      systemConfig.value.use_application_export_depot_required_strategy === 1
    ) {
      getExportDopotId(formInfo.value.data.depotId)
    } else {
      getProductList()
    }
  } else {
    tableInfo.value.data = []
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
    formInfo.value.data.exportDepotName = ''
    formInfo.value.data.exportDepotId = ''
    formInfo.value.data.exportDeptName = ''
    formInfo.value.data.exportDeptId = ''
    productInfo.value.query.queryParams.storeDepotId = ''
    formInfo.value.supDepotIds = []
  }
}
function selectExportDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.value.data.exportDepotId !== row.id) {
      tableInfo.value.data = []
      formInfo.value.data.exportDepotId = row.id
      formInfo.value.data.exportDepotName = row.name
      formInfo.value.data.exportDeptName = row.deptName ? row.deptName : ''
      formInfo.value.data.exportDeptId = row.deptId ? row.deptId : ''
    }
    productInfo.value.query.queryParams.exportDepotId = row.id
  } else {
    tableInfo.value.data = []
    formInfo.value.data.exportDepotId = ''
    formInfo.value.data.exportDepotName = ''
    formInfo.value.data.exportDeptName = ''
    formInfo.value.data.exportDeptId = ''
    productInfo.value.query.queryParams.exportDepotId = ''
  }
  getProductList()
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.value.data.deptName = row.name
    formInfo.value.data.deptId = row.id
    formInfo.value.data.depotName = ''
    formInfo.value.data.depotId = ''
    tableInfo.value.data = []
    getProductList()
  }
}
function addCart({ row, index }) {
  proxy.$fn
    .checkForm([formInfo.value.ref])
    .then(() => {
      applicationValidateSubDepot(formInfo.value.data).then((res) => {
        if (res && res.success) {
          const params = {
            depotId: formInfo.value.data.exportDepotId,
            deptId: formInfo.value.data.exportDeptId,
            targetDepotId: formInfo.value.data.depotId,
            targetDeptId: formInfo.value.data.deptId,
            orderType: 19,
            details: [row],
          }
          addApplicationCart(params).then((res) => {
            if (res && res.success) {
              proxy.$message.success('添加购物车成功')
              const currntRow = proxy.$fn.deepClone(tableInfo.value.data[index])
              currntRow.qty = ''
              currntRow.calcQty = ''
              currntRow.largeUnitQty = ''
              tableInfo.value.data[index] = currntRow
              proxy.$store.dispatch('user/getShoppingCartCounts')
              // getProductList()
            }
          })
        }
      })
    })
    .catch(() => {
      proxy.$message.warning('请按照提示输入正确数据')
    })
}
</script>

<style scoped></style>
